const mongoose = require('mongoose');
const News=require('../models/news.model');
//新增
exports.create=function(req,res,next){
    const news = new News(req.body);
    news.save().then((data) =>{
        res.json(data);
    });
}

// 修改
exports.update=function(req,res,next){
    const id=req.params.id;
    News.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
        res.json(data); //返回的是修改之前的数据
    });
}
// 删除单个
exports.remove=function(req,res,next){
    const id=req.params.id;
    News.findByIdAndDelete(id,(err,data)=>{
        res.json(data);
    });
}

// 删除多个
exports.removes=function(req,res,next){
    var ids=req.body.ids.split(',');
    if(ids.length>0){
        News.remove({_id:{$in:ids}}).then(data=>{
            res.json('message:ok'+'status:200');
        })
    }
    News.findByIdAndDelete(id,(err,data)=>{
        res.json(data);
    });
}

// 查询
exports.list=function(req,res,next){
    var page=req.body.page ? req.body.page : 1;
    var rows=req.body.rows ? req.body.rows : 10;
    var queryCondition={};
    if(req.body.dimtitle && req.body.dimtitle.trim().length>0){
        //根据查询条件搜索记录
        title=req.body.dimtitle;
        var str='(.*)'+title+'(.*)';
        queryCondition={
            "title":new RegExp(str,'g')
        }
    }else if(req.body.dimcate && req.body.dimcate.trim().length>0){
        //显示分类数据
        cate=req.body.dimcate.split(',').join('|');
        var reg=new RegExp(cate,'g');
        queryCondition={
            "cate":reg
        }
    }else{ 
        //显示全部数据
        title=req.body.title;
        queryCondition={
            "title":new RegExp(title,'i')
        }
    }
    News.paginate(queryCondition, { page: +page, limit:+rows }, function(err, result) {
        result.rows=result.docs;
        delete result.docs;
        res.json(result);
    });
}
//查询单条记录
exports.getData=function(req,res,next){
    const id=req.params.id;
    News.findById(id).then(data=>{
        res.json(data);
    })
}